﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using TXTD.Admin.Data.Entitys.System;
using TXTD.Admin.Model.Core;

namespace TXTD.Admin.Service.Utilitys.Jwt
{
    public class JwtHelper
    {
        private readonly IConfiguration _configuration;
        public JwtHelper(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        public ResultTokenModel CreateToken(SysUser user)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, user.UserCode),
                new Claim("UserId", user.UserId),
                new Claim("UserCode", user.UserCode),
                new Claim("UserCode", user.UserCode),
            };
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));
            var algorithm = SecurityAlgorithms.HmacSha256;
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            //用于验证权限的koen
            var Token = new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
                _configuration["Jwt:Issuer"],     //Issuer
                _configuration["Jwt:Audience"],   //Audience
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
                DateTime.Now.AddMinutes(30),    // 过期时间
                signingCredentials               //Credentials
            ));
            //用于刷新token的RefreshToken
            var RefreshToken = new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
                _configuration["Jwt:Issuer"],     //Issuer
                _configuration["Jwt:Audience"],   //Audience
                null,                          //Claims,
                DateTime.Now,                    //notBefore
                DateTime.Now.AddDays(1),        // 过期时间
                signingCredentials               //Credentials
            ));

            return new ResultTokenModel()
            {
                Token = Token,
                RefreshToken = RefreshToken
            };
        }

        /// <summary>
        /// 获取token信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public ClaimsPrincipal GetClaimsPrincipalByToken(string token)
        {
            try
            {
                var tokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_configuration["Jwt:SecretKey"])),
                    ClockSkew = TimeSpan.Zero,
                    ValidateLifetime = false // 不验证过期时间！！！
                };

                var jwtTokenHandler = new JwtSecurityTokenHandler();

                var claimsPrincipal =
                    jwtTokenHandler.ValidateToken(token, tokenValidationParameters, out var validatedToken);

                var validatedSecurityAlgorithm = validatedToken is JwtSecurityToken jwtSecurityToken
                                                 && jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256,
                                                     StringComparison.InvariantCultureIgnoreCase);

                return validatedSecurityAlgorithm ? claimsPrincipal : null;
            }
            catch
            {
                return null;
            }
        }
    }
}
